# encoding: utf-8
"""
编译工具:编译文件到传入文件的位置
"""
import sys
import os
import pickle
from os.path import join, dirname
from Compiler.Compiler import Compiler
from Error.Error import send_error
from loader.bytecode_writer import save_ctree


def build(path: str) -> None:
    """编译为指令集"""
    path = os.path.abspath(path)
    compile_name = os.path.splitext(os.path.split(path)[1])[0] + ".ctree"
    buildpath = join(dirname(path), compile_name)
    try:
        with open(buildpath, "wb") as file, open(path, encoding="UTF-8") as openfile:
            res = Compiler(openfile.read())
            file.write(pickle.dumps(res))
    except FileNotFoundError:
        # 顺便清理掉垃圾
        os.remove(buildpath)
        send_error("OpenFileError", path)

    except FileExistsError:
        os.remove(buildpath)
        build(path)


if __name__ == "__main__":
    file_list = sys.argv[1:]
    for i in file_list:
        build(i)
